<?php

class Filter_IndexController extends Core_Controller_Action_Standard {

    public function indexAction() {
        $this->view->someVar = 'someVal';
    }

    public function createAction() {
        if( !$this->_helper->requireUser()->isValid() ) return;
        
        $viewer = Engine_Api::_()->user()->getViewer();
        
        $this->view->form = $form = new Filter_Form_Create();
        
        if ($this->_getParam('format') !== 'smoothbox') {
            $form->removeElement('cancel');
        }
        
        if (!$this->getRequest()->isPost()) {
            return;
        }

        if (!$form->isValid($this->getRequest()->getPost())) {
            return;
        }
        
        $values = $form->getValues();
        
        // get last_id of filter_type
        $type_row = Engine_Api::_()->getItem('filter_type', $values['filter_type']);
        $last_id = Engine_Api::_()->getItemTable($type_row->type_name)->fetchRow(null, $type_row->type_name.'_id DESC')->getIdentity();
        
        $values_insert = array(
            'user_id' => $viewer->getIdentity(),
            'type_id' => $values['filter_type'],
            'title' => $values['title'],
            'enabled' => 1,
            'creation_date' => date('Y-m-d H:i:s'),
            'last_id' => $last_id,
            'last_updated_date' => date('Y-m-d H:i:s')
        );
        
        $filterTable = Engine_Api::_()->getItemTable('filter');
        $db = $filterTable->getAdapter();
        $db->beginTransaction();
        try {
            $filter = $filterTable->createRow();
            $filter->setFromArray($values_insert);
            $filter->save();
            $db->commit();
        } catch(Exception $e) {
            $db->rollBack();
            throw $e;
        }
        
        // insert into filter_values
        
        $valuesTable = Engine_Api::_()->getDbTable('values', 'filter');
        
        $db = $valuesTable->getAdapter();
        $db->beginTransaction();
        try {
            foreach ($values as $name=>$value) {
                // ignore filter_type, title elements
                if (in_array($name, array('filter_type','title'))) {
                    continue;
                }
                $name = explode('_', $name);
                if($name[2] == $values['filter_type']) {
                    $val = $valuesTable->createRow();
                    $val->criteria_id = $name[1];
                    $val->filter_id = $filter->getIdentity();
                    
                    if ($name[3] !== 'calendar') {
                        $val->value = $value;
                    } else {
                        // Convert times
                        $oldTz = date_default_timezone_get();
                        date_default_timezone_set($viewer->timezone);
                        $val_date = strtotime($value);
                        date_default_timezone_set($oldTz);
                        $value = date('Y-m-d H:i:s', $val_date);
                        $val->value = $value;
                    }
                    $val->save();
                }
            }
            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            throw $e;
        }
        
        if ($this->_getParam('format') !== 'smoothbox') {
            $form->addNotice('The new filter have been created.');
        }
        else {
            return $this->_forward('success' ,'utility', 'core', array(
                'parentRefresh' => true,
                'messages' => 'The new filter have been created.'
            ));
        }
    }

    public function editAction()
    {
        $viewer = Engine_Api::_()->user()->getViewer();
        
        $this->view->form = $form = new Filter_Form_Edit();
        
        $filter = Engine_Api::_()->getItem('filter', $this->_getParam('id'));
        $filter_type = Engine_Api::_()->getItem('filter_type', $filter->type_id);
        
        $values['filter_type'] = $filter_type->getIdentity();
        $values['title'] = $filter->title;
        $values['enabled'] = $filter->enabled;
        $values['filter_type_label'] = $filter_type->title;
        $valuesTable = Engine_Api::_()->getDbTable('values', 'filter');
        $sl_val = $valuesTable->select()
                ->setIntegrityCheck(false)
                ->from(array('v' => $valuesTable->info('name')))
                ->join(array('c' => Engine_Api::_()->getDbTable('criteria', 'filter')->info('name')), 'c.criteria_id = v.criteria_id')
                ->where('v.filter_id = ?', $filter->getIdentity());
        $filter_values = $valuesTable->fetchAll($sl_val);
       
        $filter_values_arr = array();
        foreach ($filter_values as $filter_value) {
            // item_4_2_text
            $filter_values_arr['item_'.$filter_value->criteria_id.'_'.$filter->type_id.'_'.$filter_value->element_type] = $filter_value->value;
        }
        
        $values = array_merge($values, $filter_values_arr);
        
        $form->populate($values);
        
        if (!$this->getRequest()->isPost()) {
            return;
        }
        
        if (!$form->isValid($this->getRequest()->getPost())) {
            return;
        }
        
        $values = $form->getValues();
        
        $values_insert = array(
            'user_id' => $viewer->getIdentity(),
            'type_id' => $values['filter_type'],
            'title' => $values['title'],
            'enabled' => 1,
            'modified_date' => date('Y-m-d H:i:s')
        );
        
        $filterTable = Engine_Api::_()->getItemTable('filter');
        $db = $filterTable->getAdapter();
        $db->beginTransaction();
        try {
            $filter->setFromArray($values_insert);
            $filter->save();
            $db->commit();
        } catch(Exception $e) {
            $db->rollBack();
            throw $e;
        }
        
        // insert into filter_values
        
        $valuesTable = Engine_Api::_()->getDbTable('values', 'filter');
        
        $db = $valuesTable->getAdapter();
        $db->beginTransaction();
        try {
            foreach ($values as $name=>$value) {
                // ignore filter_type, title elements
                if (in_array($name, array('filter_type','title'))) {
                    continue;
                }
                $name = explode('_', $name);
                if($name[2] == $values['filter_type']) {
                    $val = $valuesTable->fetchRow(array('criteria_id = ?' => $name[1], 'filter_id' => $filter->getIdentity()));
                    $val->criteria_id = $name[1];
                    $val->filter_id = $filter->getIdentity();
                    
                    if ($name[3] !== 'calendar') {
                        $val->value = $value;
                    } else {
                        // Convert times
                        $oldTz = date_default_timezone_get();
                        date_default_timezone_set($viewer->timezone);
                        $val_date = strtotime($value);
                        date_default_timezone_set($oldTz);
                        $value = date('Y-m-d H:i:s', $val_date);
                        $val->value = $value;
                    }
                    
                    $val->save();
                }
            }
            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            throw $e;
        }
        
        if ($this->_getParam('format') !== 'smoothbox') {
            $form->addNotice('The filter have been changed.');
        }
        else {
            return $this->_forward('success' ,'utility', 'core', array(
                'parentRefresh' => true,
                'messages' => 'The filter have been changed.'
            ));
        }
        
    }
    
    public function deleteAction()
    {
        $this->view->form = new Filter_Form_Delete();
        
        if (!$this->getRequest()->isPost()) {
            return;
        }
        // delete on filter value
        $valuesTable = Engine_Api::_()->getDbTable('values', 'filter');
        $values = $valuesTable->fetchAll(array('filter_id = ?' => $this->_getParam('id')));
        $db = $valuesTable->getAdapter();
        $db->beginTransaction();
        try {
            foreach ($values as $value) {
                $value->delete();
            }
            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            throw $e;
        }
        
        // delete on filter
        $filter = Engine_Api::_()->getItem('filter', $this->_getParam('id'));
        $db = $filter->getTable()->getAdapter();
        $db->beginTransaction();
        try {
            $filter->delete();
            $db->commit();
        } catch(Exception $e) {
            $db->rollBack();
            throw $e;
        }
        
        return $this->_forward('success' ,'utility', 'core', array(
			'parentRefresh' => true,
			'messages' => 'The filter have been deleted.'
		));
    }

    public function manageAction() {
        if( !$this->_helper->requireUser()->isValid() ) return;
        
        // default is 'user'
        $this->view->type_param = $type_param = $this->_getParam('filter_type', 'user');
        
        // get area structure
        $structure = array();
        foreach (Engine_Api::_()->getDbTable('types', 'filter')->fetchAll(array('type_name = ?' => $type_param)) as $type) {
            foreach (Engine_Api::_()->getDbTable('criteria', 'filter')->fetchAll() as $criteria) {
                if ($criteria->type_id == $type->getIdentity()) {
                    $structure[$type->type_name][$criteria->criteria_name.'-'.$criteria->element_type] = $criteria->title;
                }
            }
        }

        $this->view->title_struc = $structure;
        
        // get filter type for tab style
        $this->view->filter_types = Engine_Api::_()->getDbTable('types', 'filter')->fetchAll();
        
        $filterTable = Engine_Api::_()->getItemTable('filter');
        $select = $filterTable->select()
                ->setIntegrityCheck(false)
                ->from(array('f' => $filterTable->info('name')))
                ->join(array('t' => Engine_Api::_()->getItemTable('filter_type')->info('name')),'f.type_id = t.type_id', array('type_id','type_name','type_title' => 't.title'))
                ->where('f.user_id = ?', Engine_Api::_()->user()->getViewer()->getIdentity())
                ->where('t.type_name = ?', $type_param)
//                ->where('f.enabled = ?', 1)
                ;
        
        $filters = $filterTable->fetchAll($select);
        
        // get list filters of user
        $filters_data = array();
        $count = 0;
        foreach ($filters as $filter) {
            $filters_data[$count]['filter_id'] = $filter->getIdentity();
            $filters_data[$count]['filter_title'] = $filter->title;
            $filters_data[$count]['filter_type_title'] = $filter->type_title;
            $filters_data[$count]['filter_type'] = $filter->type_name;
            
            // get list criteria by filter type_id
            $criteriaList = Engine_Api::_()->getDbTable('criteria', 'filter')->fetchAll(array(
                            'type_id = ?' => $filter->type_id
                        ));

            $values = array();
            foreach ($criteriaList as $criteria) {
                // get from table value by filter_id and criteria_id
                $sl_val = Engine_Api::_()->getDbTable('values', 'filter')->select()
                        ->where('filter_id = ?' , $filter->getIdentity())
                        ->where('criteria_id = ?' , $criteria->getIdentity());
                $value = Engine_Api::_()->getDbTable('values', 'filter')->fetchAll($sl_val)
                                        ->toArray();
                                
                $filters_data[$count][$criteria->criteria_name] = $value[0]['value'];
            }            
            $count++;
        }
        
        $this->view->filters = $paginator = Zend_Paginator::factory($filters_data);
        $paginator->setItemCountPerPage(1);
        $paginator->setCurrentPageNumber($this->_getParam('page', 1));               
    }

}